import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import {
  devtools,
  persist,
  createJSONStorage,
  subscribeWithSelector
} from "zustand/middleware";

export const createCounterStore = create(
  immer(
    devtools(
      subscribeWithSelector(
        persist(
          (set, get) => ({
            price: 100,
            color: "red",
            count: 10
            // increment: () =>
            //   set((state) => {
            //     state.count += 1;
            //   }),
            // decrement: () =>
            //   set((state) => {
            //     state.count -= 1;
            //   }),
            // getTotal: () => get().price * get().count
          }),
          {
            name: "counterStore",
            partialize: (state) =>
              Object.fromEntries(
                // Object.entries(state).filter(([key]) => key !== "price")
                Object.entries(state).filter(
                  ([key]) => !["price"].includes(key)
                )
              ),
            storage: createJSONStorage(() => sessionStorage)
          }
        )
      ),
      { enabled: true, name: "Counter Store" }
    )
  )
);

export const increment = () => {
  createCounterStore.setState((state) => {
    state.count += 1;
  });
};
export const decrement = () => {
  createCounterStore.setState((state) => {
    state.count -= 1;
  });
};
export const getTotal = () => {
  return (
    createCounterStore.getState().price * createCounterStore.getState().count
  );
};
